<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

            <el-row>
                <!--<el-col :span="4.5">
                  <el-form-item label="项目编号" prop="projectCode">
                    <el-select v-model="queryParams.projectCode" filterable placeholder="请输入或选择项目编号" style="width: 200px;">
                      <el-option
                          v-for="item in projectOptions"
                          :key="item"
                          :label="item"
                          :value="item"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>-->
                <!-- 下拉框+模糊搜索 -->
                <el-col :span="4">
                    <el-form-item label="间接明细名" prop="nameId" label-width="90px">
                        <el-select v-model="queryParams.nameId" placeholder="请选择间接明细名" clearable style="width: 170px;">
                            <el-option
                                    v-for="dict in name_id"
                                    :key="dict.value"
                                    :label="dict.label"
                                    :value="dict.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <!--<el-col :span="4">
                  <el-form-item label="期数" prop="number">
                    <el-input
                        v-model="queryParams.number"
                        placeholder="请输入期数"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                  </el-form-item>
                </el-col>-->
            </el-row>
            <el-row>
                <el-col :span="4">
                    <el-form-item label="创建人" prop="createBy">
                        <el-input
                                v-model="queryParams.createBy"
                                placeholder="请输入创建人"
                                clearable
                                @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="创建时间">
                        <el-date-picker
                                v-model="daterangeCreateTime"
                                value-format="YYYY-MM-DD"
                                type="daterange"
                                range-separator="-"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="更新人" prop="updateBy">
                        <el-input
                                v-model="queryParams.updateBy"
                                placeholder="请输入更新人"
                                clearable
                                @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="更新时间">
                        <el-date-picker
                                v-model="daterangeUpdateTime"
                                value-format="YYYY-MM-DD"
                                type="daterange"
                                range-separator="-"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['system:indirect:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['system:indirect:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['system:indirect:remove']"
                >删除
                </el-button>
            </el-col>
            <!-- 导入 -->
            <el-col :span="1.5">
                <el-button
                        type="info"
                        plain
                        icon="Upload"
                        @click="handleImport"
                        v-hasPermi="['system:indirect:import']"
                >导入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['system:indirect:export']"
                        v-if="false">导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="indirectList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column align="center" prop="id" v-if="false"/>
            <el-table-column align="center" prop="areaId" v-if="false"/>
            <el-table-column label="项目编号" align="center" prop="projectCode" sortable v-if="false"/>
            <el-table-column label="间接明细名" align="center" prop="nameId" sortable>
                <template #default="scope">
                    <dict-tag :options="name_id" :value="scope.row.nameId"/>
                </template>
            </el-table-column>
            <el-table-column label="施工借方发生额合计" align="center" prop="totalNoTax" sortable/>
            <el-table-column label="已收账款" align="center" prop="received" sortable/>
            <el-table-column label="累计已发生成本" align="center" prop="realTotalWithTax" sortable/>
            <el-table-column label="预计总成本" align="center" prop="contractWithTax" sortable/>
            <el-table-column label="期数" align="center" prop="dateNumber" sortable/>
            <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column label="创建人" align="center" prop="createBy" v-if="false"/>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable v-if="false"/>
            <el-table-column label="更新人" align="center" prop="updateBy" v-if="false"/>
            <el-table-column label="更新时间" align="center" prop="updateTime" width="180" sortable v-if="false">
                <!--<template #default="scope">-->
                <!--  <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>-->
                <!--</template>-->
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                               v-hasPermi="['system:indirect:edit']">修改
                    </el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                               v-hasPermi="['system:indirect:remove']">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改间接费用对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form ref="indirectRef" :model="form" :rules="rules" label-width="80px" style="width: 500px;">

                <!-- 下拉框+模糊搜索 -->
                <!--<el-form-item label="项目编号" prop="projectCode" label-width="140px">
                  <el-select v-model="form.projectCode" filterable placeholder="请输入或选择项目编号" style="width: 200px;">
                    <el-option
                        v-for="item in projectOptions"
                        :key="item"
                        :label="item"
                        :value="item"
                    />
                  </el-select>
                </el-form-item>-->
                <!--<el-form-item label="期数" prop="number" label-width="140px">
                  <el-input-number v-model="form.number" placeholder="期" step-strictly />
                </el-form-item>-->
                <el-form-item label="间接明细名" prop="nameId" label-width="140px">
                    <el-select v-model="form.nameId" placeholder="请选择间接明细名" style="width: 200px;">
                        <el-option
                                v-for="dict in name_id"
                                :key="dict.value"
                                :label="dict.label"
                                :value="parseInt(dict.value)"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="施工借方发生额合计" prop="totalNoTax" label-width="140px">
                    <el-input v-model="form.totalNoTax" placeholder="请输入账面工程施工借方发生额合计"/>
                </el-form-item>
                <el-form-item label="已收账款" prop="received" label-width="140px">
                    <el-input v-model="form.received" placeholder="请输入已收账款"/>
                </el-form-item>
                <el-form-item label="累计已发生成本" prop="realTotalWithTax" label-width="140px">
                    <el-input v-model="form.realTotalWithTax" placeholder="请输入累计已发生成本"/>
                </el-form-item>
                <el-form-item label="预计总成本" prop="contractWithTax" label-width="140px">
                    <el-input v-model="form.contractWithTax" placeholder="请输入预计总成本"/>
                </el-form-item>
                <el-form-item label="备注" prop="remark" label-width="140px">
                    <el-input v-model="form.remark" placeholder="请输入备注"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>


    <!-- 间接费用导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <div class="centered">
            <el-form-item label="期数选择" prop="dateNumber" class="custom-label">
                <el-date-picker type="month"
                                v-model="upload.dateNumber"
                                format="YYYY-MM"
                                value-format="YYYY-MM"
                                :style="{width: '100%', fontSize: '18px'}"
                                placeholder="请选择期数"
                                clearable
                                style="width: 200px;">
                </el-date-picker>
            </el-form-item>
        </div>
        <el-upload
                ref="uploadRef"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '&dateNumber=' + upload.dateNumber"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag

        >
            <el-icon class="el-icon--upload">
                <upload-filled/>
            </el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
                <div class="el-upload__tip text-center">
                    <!--<div class="el-upload__tip">
                      <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的 “材料采购明细”
                    </div>-->
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                             @click="importTemplate">下载模板
                    </el-link>
                </div>
            </template>
        </el-upload>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="Indirect">
    import {listIndirect, getIndirect, delIndirect, addIndirect, updateIndirect} from "@/api/system/indirect";
    import { getToken } from "@/utils/auth";
    const {proxy} = getCurrentInstance();
    const {name_id} = proxy.useDict('name_id');

    const indirectList = ref([]);
    const projectOptions = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const title = ref("");
    const daterangeCreateTime = ref([]);
    const daterangeUpdateTime = ref([]);

    // 获取当前 URL 中的查询参数部分
    const queryString = window.location.search;
    // 使用 URLSearchParams 对象解析查询参数
    const urlParams = new URLSearchParams(queryString);

    const nameSort = (a, b) => {
        return a.nameId.localeCompare(b.nameId, 'zh');
    };

    const data = reactive({
        form: {},
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            projectCode: null,
            nameId: null,
            totalNoTax: null,
            received: null,
            realTotalWithTax: null,
            contractWithTax: null,
            remark: null,
            createBy: null,
            createTime: null,
            updateBy: null,
            updateTime: null,
            areaId: urlParams.get('areaId')
        },
        rules: {
            /*projectCode: [
              { required: true, message: "项目编号不能为空", trigger: "blur" }
            ],*/
            nameId: [
                {required: true, message: "间接明细名不能为空", trigger: "blur"}
            ],
            // number: [
            //   { required: true, message: '请输入或选择期数', trigger: 'blur'},
            //   { pattern: /^[1-9]\d*$/, message: '期数不可小于1', trigger: 'blur'}
            // ],
        }
    });

    const {queryParams, form, rules} = toRefs(data);

    /** 查询间接费用列表 */
    function getList() {
        loading.value = true;
        queryParams.value.params = {};
        console.log("areaId: " + queryParams.value.areaId);
        queryParams.value.params["areaId"] = queryParams.value.areaId;
        console.log("name_id:" + queryParams.nameId)
        if (null != daterangeCreateTime && '' !== daterangeCreateTime) {
            queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
            queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
        }
        if (null != daterangeUpdateTime && '' !== daterangeUpdateTime) {
            queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
            queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
        }
        listIndirect(queryParams.value).then(response => {
            indirectList.value = response.dataList.rows;
            projectOptions.value = response.projectCodeList;
            total.value = response.dataList.total;
            loading.value = false;
        });
    }

    // 取消按钮
    function cancel() {
        open.value = false;
        reset();
    }

    // 表单重置
    function reset() {
        form.value = {
            id: null,
            projectCode: null,
            nameId: null,
            totalNoTax: null,
            received: null,
            realTotalWithTax: null,
            contractWithTax: null,
            remark: null,
            createBy: null,
            createTime: null,
            updateBy: null,
            updateTime: null,
            // number: 1
        };
        proxy.resetForm("indirectRef");
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        daterangeCreateTime.value = [];
        daterangeUpdateTime.value = [];
        proxy.resetForm("queryRef");
        handleQuery();
    }

    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item.id);
        single.value = selection.length !== 1;
        multiple.value = !selection.length;
    }

    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        form.value.areaId = queryParams.value.areaId;
        open.value = true;
        title.value = "添加间接费用";
    }

    /** 修改按钮操作 */
    function handleUpdate(row) {
        reset();
        const _id = row.id || ids.value
        getIndirect(_id).then(response => {
            form.value = response.data;
            open.value = true;
            title.value = "修改间接费用";
        });
    }

    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["indirectRef"].validate(valid => {
            if (valid) {
                if (form.value.id != null) {
                    updateIndirect(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                    });
                } else {
                    addIndirect(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        getList();
                    });
                }
            }
        });
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
        const _ids = row.id || ids.value;
        proxy.$modal.confirm('是否确认删除间接费用编号为"' + _ids + '"的数据项？').then(function () {
            return delIndirect(_ids);
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
    }


    /** 导出按钮操作 */
    function handleExport() {
        proxy.download('system/indirect/export', {
            ...queryParams.value
        }, `indirect_${new Date().getTime()}.xlsx`)
    }

    /*** 直接费用导入参数 */
    const upload = reactive({
        // 是否显示弹出层（明细导入）
        open: false,
        // 弹出层标题（明细导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的明细数据
        updateSupport: 0,
        // 期数
        dateNumber: ref(getCurrentYearMonth()),
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: import.meta.env.VITE_APP_BASE_API + "/system/indirect/importData?areaId=" + urlParams.get('areaId')
    });
    console.log(upload.url)
    console.log("dateNumber: " + upload.dateNumber)
    /** 导入按钮操作 */
    function handleImport() {
        upload.title = "间接费用导入";
        upload.open = true;
    };

    /** 下载模板操作 */
    function importTemplate() {
        proxy.download("system/indirect/importTemplate", {}, `间接费用模板.xlsx`);
    };
    /**文件上传中处理 */
    const handleFileUploadProgress = (event, file, fileList) => {
        upload.isUploading = true;
    };
    /** 文件上传成功处理 */
    const handleFileSuccess = (response, file, fileList) => {
        upload.open = false;
        upload.isUploading = false;
        proxy.$refs["uploadRef"].handleRemove(file);
        proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>"
            + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
        getList();
    };
    // 获取当前年月的函数
    function getCurrentYearMonth() {
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 补足月份的两位数
        return `${year}-${month}`;
    }

    /** 提交上传文件 */
    function submitFileForm() {
        proxy.$refs["uploadRef"].submit();
    };


    getList();
</script>

<style>
    .centered {
        display: flex;
        justify-content: center;
    }

    .custom-label .el-form-item__label {
        font-size: 18px;
    }
</style>


